#include <iostream>
#include <mariadb/mysql.h>
#include <unistd.h>

int Add(MYSQL *mysql)
{
    const char *str = "insert into test_tb values(null, 18, '小张', 78.9);";
    int ret = mysql_query(mysql, str);
    if (ret)
    {
        std::cout << "mysql_query add failed:>" << mysql_error(mysql) << std::endl;
        return -1;
    }
    return 0;
}

int Mod(MYSQL *mysql)
{
    const char *str = "update test_tb set name = '小王' where id =2;";
    int ret = mysql_query(mysql, str);
    if (ret)
    {
        std::cout << "mysql_query mod failed:>" << mysql_error(mysql) << std::endl;
        return -1;
    }
    return 0;
}

int Del(MYSQL *mysql)
{
    const char *str = "delete from test_tb where id = 1;";
    int ret = mysql_query(mysql, str);
    if (ret)
    {
        std::cout << "mysql_query del failed:>" << mysql_error(mysql) << std::endl;
        return -1;
    }
    return 0;
}

int Get(MYSQL *mysql)
{
    const char *str = "select * from test_tb;";
    int ret = mysql_query(mysql, str);
    if (ret)
    {
        std::cout << "mysql_query get failed:>" << mysql_error(mysql) << std::endl;
        return -1;
    }
    MYSQL_RES *res = mysql_store_result(mysql);
    int row_num = mysql_num_rows(res);
    int col_num = mysql_num_fields(res);
    for (int i = 0; i < row_num; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for (int j = 0; j < col_num; j++)
        {
            std::cout << row[j] << "\t";
        }
        std::cout << std::endl;
    }

    mysql_free_result(res);

    return 0;
}

int main()
{
    MYSQL *mysql = mysql_init(nullptr);
    bool ret = mysql_real_connect(mysql, "127.0.0.1", "root", "dtxawrz26080", "test_db", 0, nullptr, 0);
    if (!ret)
    {
        std::cout << "mysql_real_connect failed:>" << mysql_error(mysql) << std::endl;
        return 1;
    }
    mysql_set_character_set(mysql, "utf8");

    // Add(mysql);
    // Add(mysql);
    Mod(mysql);
    Del(mysql);
    Get(mysql);

    mysql_close(mysql);

    return 0;
}